# src/api/auth_api.py
from flask import Blueprint, request, jsonify
from src.service.auth_service import register_user, login_user
from src.utils.logger import get_logger

# 创建Blueprint（模块化路由）
auth_bp = Blueprint("auth", __name__, url_prefix="/api/auth")
logger = get_logger(__name__)

@auth_bp.route("/register", methods=["POST"])
def register():
    """用户注册接口"""
    try:
        # 获取请求参数
        data = request.get_json()
        username = data.get("username")
        password = data.get("password")
        real_name = data.get("real_name")
        contact_info = data.get("contact_info")
        address = data.get("address", "")
        user_role = data.get("user_role", "买家")
        
        # 调用业务逻辑
        success, msg = register_user(
            username=username,
            password=password,
            real_name=real_name,
            contact_info=contact_info,
            address=address,
            user_role=user_role
        )
        
        # 返回结果
        if success:
            return jsonify({"success": True, "message": msg}), 200
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"注册接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@auth_bp.route("/login", methods=["POST"])
def login():
    """用户登录接口"""
    try:
        # 获取请求参数
        data = request.get_json()
        username = data.get("username")
        password = data.get("password")
        
        # 调用业务逻辑
        success, result = login_user(username=username, password=password)
        
        # 返回结果
        if success:
            return jsonify({
                "success": True,
                "authenticated": True,
                "user_info": result
            }), 200
        else:
            return jsonify({
                "success": False,
                "authenticated": False,
                "error": result
            }), 401
    except Exception as e:
        logger.error(f"登录接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500